<?php
/**
 * Description of User
 *
 * @author Admin
 */

class Main_Model_AdminUser extends WOW_Model_Acl_Abstract
{
    
    public function getUserById($id)
    {
        $id = (int) $id;
        return $this->getResource('Adminuser')->getUserById($id);
    }

    public function getUserByUserName($name)
    {
        return $this->getResource('Adminuser')
                    ->getUserByUserName($name);
    }
    public function getUserByUserNamePassword($name, $pwd)
    {
        return $this->getResource('Adminuser')
                    ->getUserByUserNamePassword($name, $pwd);
    }

    protected function _saveUser(Zend_Form $form, array $info, $defaults=array())
    {
        if (!$form->isValid($info))
        {
            return false;
        }

        $data = $form->getValues();
        foreach ($defaults as $col => $value)
        {
            $data[$col] = $value;
        }
        if($data['id'] !='')
        {
            $data['updated_at'] = date('Y-m-d H:i:s');
        }
        else
        {
            $data['created_at'] = date('Y-m-d H:i:s');
            $data['updated_at'] = date('Y-m-d H:i:s');
        }
         
        $user = ($data['id'] !='') ? $this->getResource('Adminuser')->getUserById($data['id']) : null;

        return $this->getResource('Adminuser')->saveRow($data, $user);
        
    }

    public function saveUser($post)
    {
        $form = $this->getForm('AdminuserNewuser');
        return $this->_saveUser($form, $post);
    }

    
    public function getAllUsers()
    {
        return $this->getResource('Adminuser')->getAllUsers();
    }

    public function getResourceId()
    {
        return 'Adminuser';
    }

    #@ TODO:: needs to be worked on ACL later
    public function setAcl(WOW_Acl_Interface $acl)
    {
        if (!$acl->has($this->getResourceId())) 
        {
            $acl->add($this)->allow('Normal', $this, array('register'))
            ->allow('Moderator', $this, array('saveUser'))
                    ->allow('Admin', $this);
        }
        $this->_acl = $acl;
        return $this;
    }

    public function getAcl()
    {
        if (null === $this->_acl) {
            $this->setAcl(new Main_Model_Acl_Main());
        }
        return $this->_acl;
    }

    /**
     * Delete a user
     *
     * @param int|Storefront_Resource_User_Item_Interface $user
     * @return boolean
     */
    public function deleteUser($user)
    {
        if ($user instanceof Main_Resource_AdminUser_Item_Interface) {
            $userId = (int) $user->userId;
        } else {
            $userId = (int) $user;
        }

        $user = $this->getUserById($userId);

        if (null !== $user) {
            $user->delete();
            return true;
        }
        else
             throw new WOW_Exception('Unknown user');
        
        return false;
    }
}
?>
